//
//  YTDriverManagerViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/7/18.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTDriverManagerViewModel.h"
#import "YTDriverTeamServices.h"
#import "YTTeamDriverModel.h"

@interface YTDriverManagerViewModel ()
@property (strong, nonatomic, readwrite) RACCommand *deleteDriverCommand;
@end

@implementation YTDriverManagerViewModel
- (void)initialize {
    [super initialize];
    _dataArray = [NSMutableArray array];
    self.page = 1;
    [self loadData];
    [self deleteDriver];
}

#pragma mark - 加载数据

- (void)loadData {
    @weakify(self);
    self.requestRemoteDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary *input) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            @strongify(self);
            self.page = 1;
            [self.dataArray removeAllObjects];
        }];
    }];
    // 加载更多
    self.loadMoreDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary *input) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            self.page++;
        }];
    }];
}

#pragma mark - 删除司机

- (void)deleteDriver {
    _deleteDriverCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"driverId"] = input;
        return [YTDriverTeamServices deleteDriverFromTeam:dict];
    }];
}

#pragma mark - Private

- (void)loadDataWithSubscriber:(id<RACSubscriber>)subscriber {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"userId"] = [YTUtilityManager manager].userModel.userId;
    dict[@"page"] = [NSString stringWithFormat:@"%zd", self.page];
    [[YTDriverTeamServices loadDriverList:dict] subscribeNext:^(NSDictionary *response) {
        NSDictionary *data = response[@"responseData"];
        NSArray<YTTeamDriverModel *> *dataArray = [NSArray yy_modelArrayWithClass:[YTTeamDriverModel class] json:data[@"dataList"]];
        [self.dataArray addObjectsFromArray:dataArray];
        [subscriber sendNext:dataArray];
        [subscriber sendCompleted];
    }];
}

@end
